/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.event.AfterNeedsActiveEventHandler;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.Task;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * An abstract superclass for {@link Command} implementations that want to verify the provided task is always active (ie. not suspended).
 * 用于{@link Command}实现的抽象超类，用于验证提供的任务始终处于活动状态（即未挂起）
 */
public abstract class NeedsActiveTaskCmd<T> implements Command<T>, Serializable {

    private static final long serialVersionUID = 1L;

    protected String taskId;
    /**
     * 是否需要验证task是否存在
     */
    protected Boolean isTaskIdValid = true;
    /**
     * 产品标识 通过上下文获取
     */
    private String prod;
    /**
     * 业务bean信息 通过上下文获取
     */
    private Map<String, Object> bean;

    public NeedsActiveTaskCmd(String taskId, String prod, Map<String, Object> bean) {
        this.taskId = taskId;
        this.prod = prod;
        this.bean = bean;
    }

    public NeedsActiveTaskCmd(Boolean isTaskIdValid, String prod, Map<String, Object> bean) {
        this.isTaskIdValid = isTaskIdValid;
        this.prod = prod;
        this.bean = bean;
    }

    public String getTaskId() {
        return taskId;
    }

    @Override
    public T execute(CommandContext commandContext) {
        T result = null;
        if (!isTaskIdValid) {
            buildBeanAndProdInfo(commandContext);
            result = execute(commandContext, null);
        } else {
            if (taskId == null) {
                throw new ActivitiIllegalArgumentException("taskId is null");
            }
            TaskEntity task = commandContext.getTaskEntityManager().findById(taskId);
            if (task == null) {
                throw new ActivitiObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
            }
            buildBeanAndProdInfo(commandContext);
            commandContext.addAttribute("taskId", taskId);
            if (task.isSuspended()) {
                throw new ActivitiException(getSuspendedTaskException());
            }
            result = execute(commandContext, task);
        }
        // 执行后事件的触发逻辑
        List<AfterNeedsActiveEventHandler> afterSubmitEvents = // 实例化自定义的任务执行后事件对象
                commandContext.getProcessEngineConfiguration().getCustomAfterSubmitEvents(); // 触发任务执行后事件
        for (AfterNeedsActiveEventHandler afterNeedsActiveEventHandler : afterSubmitEvents) {
//            afterNeedsActiveEventHandler.execute(commandContext);
        }
        return result;
    }

    private void buildBeanAndProdInfo(CommandContext commandContext) {
        if (bean != null) {
            commandContext.addAttribute(CommandContext.BEAN, bean);
        }
        if (prod != null) {
            commandContext.addAttribute(CommandContext.PROD, prod);
        }
    }

    /**
     * Subclasses must implement in this method their normal command logic. The provided task is ensured to be active.
     */
    protected abstract T execute(CommandContext commandContext, TaskEntity task);

    protected void addTaskComment(String taskId, String processInstanceId, String type, String message) {
        CommandContext commandContext = Context.getCommandContext();
        commandContext.getProcessEngineConfiguration().getTaskService().addComment(taskId, processInstanceId,
                type, message);
    }

    /**
     * Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended.
     */
    protected String getSuspendedTaskException() {
        return "Cannot execute operation: task is suspended";
    }


    public void executeBeforeHandler(BpmnModel bpmnModel, TaskEntity task,
                                     CustomEvent.CustomEventEnum customEventEnum,
                                     String comment, OperatorEnum operatorEnumType) {
        invokeCustomerEvent(bpmnModel, task, customEventEnum, comment, operatorEnumType);
    }

    public void executeAfterHandler(BpmnModel bpmnModel, TaskEntity task,
                                    CustomEvent.CustomEventEnum customEventEnum,
                                    String comment, OperatorEnum operatorEnumType) {
        invokeCustomerEvent(bpmnModel, task, customEventEnum, comment, operatorEnumType);
    }


    private void invokeCustomerEvent(BpmnModel bpmnModel, Task task, CustomEvent.CustomEventEnum type
            , String comment, OperatorEnum operatorEnumType) {
        CommandContext commandContext = Context.getCommandContext();
        bean = (Map<String, Object>) commandContext.getAttribute(CommandContext.BEAN);
        FlowElement flowElement = bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());
        List<CustomEvent> list = new ArrayList<>();
        if (flowElement instanceof KaiteBaseUserTask) {
            KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;
            list = kaiteBaseUserTask.getCustomEventListeners();
        }
        if (list.size() == 0) {
            return;
        }


        //执行自定义事件
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper()
                .invokeEvent(list, task.getName(), task.getTaskDefinitionKey(), "",
                        type, commandContext, comment, task.getId(), operatorEnumType);

        //自定义字段赋值
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().updateBeanInfo
                (bpmnModel.getMainProcess().getProcessConfig(), task.getBusinessKey(),
                        "", commandContext);
    }


    private String getProd() {
        return prod;
    }

    private Map<String, Object> getBean() {
        return bean;
    }

}
